package com.dz.scrm.mvp.presenter

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.OnLifecycleEvent
import com.dz.scrm.app.config.*
import com.dz.scrm.mvp.model.entity.*
import com.dz.scrm.mvp.model.repository.UserRepository
import com.dz.scrm.utils.LoggerUtils
import com.dz.scrm.utils.io_main_retry
import com.google.gson.Gson
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.disposables.Disposable
import me.jessyan.art.di.component.AppComponent
import me.jessyan.art.mvp.BasePresenter
import me.jessyan.art.mvp.Message
import me.jessyan.art.utils.PermissionUtil
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber

/**
 * 作者：fanda
 * 日期：2021/4/21 19:33
 * 描述：用户操作 P 层
 */
class UserPresenter(private val appComponent: AppComponent, val rxPermissions: RxPermissions) :
        BasePresenter<UserRepository>(appComponent.repositoryManager().createRepository(UserRepository::class.java)) {

    private val mErrorHandler = appComponent.rxErrorHandler()

    // 生命周期走在 onCreate 时会回调此方法
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate() {
        // 这里没用，只是说明有这样的一种解耦处理
    }

    /***
     * 获取验证码
     */
    fun getCode(msg: Message) {
        msg.target.showLoading()//显示下拉刷新的进度条
        val phoneNum = msg.obj as String
        mModel.getCode(phoneNum).doOnSubscribe { d: Disposable ->
            addDispose(d)
        }.compose(io_main_retry()).doFinally {
            msg.target.hideLoading()
            msg.handleMessageToTarget() //方法最后必须调HandleMessageToTarget,将消息所有引用清空后回收进消息池
        }.subscribe(object : ErrorHandleSubscriber<BaseResponse<MsgCodeBean?>>(mErrorHandler) {
            override fun onNext(response: BaseResponse<MsgCodeBean?>) {
                if (response.isSuccess()) {
                    if (response.data?.error_code == CODE_REQUEST_ERROR) {
                        msg.target.showMessage(response.data.error_description ?: "")
                    } else {
                        msg.obj = response.data
                        msg.what = WHAT_LOGIN_GAECODE_SUCCESS
                    }
                } else {
                    msg.target.showMessage(response.msg ?: "")
                }
                LoggerUtils.d(response.toString())
            }
        })
    }


    /***
     * Login
     */
    fun Login(msg: Message, phoneNum: String, code: String) {
        msg.target.showLoading()//显示下拉刷新的进度条
        mModel.Login(phoneNum, code).doOnSubscribe { d: Disposable ->
            addDispose(d)
        }.compose(io_main_retry()).doFinally {
            msg.target.hideLoading()
            msg.handleMessageToTarget() //方法最后必须调HandleMessageToTarget,将消息所有引用清空后回收进消息池
        }.subscribe(object : ErrorHandleSubscriber<BaseResponse<LoginBean?>>(mErrorHandler) {
            override fun onNext(response: BaseResponse<LoginBean?>) {
                if (response.isSuccess()) {
                    if (response.data?.error_code == CODE_REQUEST_ERROR) {
                        msg.target.showMessage(response.data.error_description ?: "")
                    } else {
                        msg.what = WHAT_LOGIN_SUCCESS
                        msg.obj = response.data
                        LoggerUtils.d(response.toString())
                    }
                } else {
                    msg.target.showMessage(response.msg ?: "")
                }
            }
        })
    }

    /***
     * checkCompany
     */
    fun checkCompany(msg: Message, phoneNum: String, tenantId: String, verify: String,registrationId:String) {
        msg.target.showLoading()//显示下拉刷新的进度条
        mModel.CheckCompany(phoneNum, tenantId, verify,registrationId).doOnSubscribe { d: Disposable ->
            addDispose(d)
        }.compose(io_main_retry()).doFinally {
            msg.target.hideLoading()
            msg.handleMessageToTarget() //方法最后必须调HandleMessageToTarget,将消息所有引用清空后回收进消息池
        }.subscribe(object : ErrorHandleSubscriber<BaseResponse<CompanyInfoBean?>>(mErrorHandler) {
            override fun onNext(response: BaseResponse<CompanyInfoBean?>) {
                if (response.isSuccess()) {
                    if (response.data?.error_code == CODE_REQUEST_ERROR) {
                        msg.target.showMessage(response.data.error_description ?: "")
                    } else {
                        msg.what = WHAT_CHECK_COMPANY_SUCCESS
                        msg.obj = response.data
                        LoggerUtils.d(Gson().toJson(response))
                    }
                } else {
                    msg.target.showMessage(response.msg ?: "")
                }
            }
        })
    }

}